package com.breaker.kata.leetcode;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;

public class ValidParenthesis {

    public boolean isValid(String s) {
        Map<Character, Character> parenthesis = new HashMap<>();
        parenthesis.put('(', ')');
        parenthesis.put('[', ']');
        parenthesis.put('{', '}');
        parenthesis.put('?', '?');

        LinkedList<Character> stack = new LinkedList<>(){{add('?');}};

        if (s.length() > 0 && parenthesis.get(s.charAt(0)) == null) {
            return false;
        }
        for (char bracket : s.toCharArray()) {
            if (parenthesis.containsKey(bracket)) {
                stack.addLast(bracket);
            } else if (parenthesis.get(stack.removeLast()) != bracket) {
                return false;
            }
        }
        return stack.size() == 1;
    }
}
